import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {
  View,
  TouchableOpacity,
  StyleSheet,
  Animated,
  Easing,
  FlatList,
} from 'react-native';
import {BasicText} from '../kit/text';
import {normalize} from '../utils/adapter';
import {ScreenHeight, ScreenWidth, usableScreenHeight} from '../config/devices';

type Props<P = any> = {
  onDismiss?: () => void;
  params?: P;
};

const Header = React.memo(function ({onDismiss}: Props): JSX.Element {
  return (
    <View style={styles.header_view}>
      <BasicText color="hsla(0,0%,100%,.6)">选集</BasicText>
      <TouchableOpacity onPress={onDismiss}>
        <BasicText color="hsla(0,0%,100%,.6)">关闭</BasicText>
      </TouchableOpacity>
    </View>
  );
});

const EpisodeTabs = React.memo(function ({
  length,
}: {
  length: number;
}): JSX.Element {
  const [tabs] = useState<number>(Math.ceil(length / 50));

  const nums = useMemo(() => {
    let numsArr: string[] = [];
    numsArr = new Array(tabs).fill(0).map((v, i) => {
      let index = i;
      let endIndex = i + 1;
      return `${index * 50 + 1}-${endIndex * 50}`;
    });
    return numsArr;
  }, [tabs]);

  return (
    <View style={styles.episodes_tabs}>
      {nums.map(text => (
        <TouchableOpacity key={text}>
          <BasicText color="hsla(0,0%,100%,.6)">{text}</BasicText>
        </TouchableOpacity>
      ))}
    </View>
  );
});

const EpisodesModal = function ({onDismiss, params}: Props): JSX.Element {
  const [episodes] = useState<Array<number>>(
    new Array(50).fill(0).map((v, i) => i + 1),
  );
  const offsetRef = useRef(new Animated.Value(ScreenHeight + 1000)).current;

  const startAnimated = useCallback(() => {
    Animated.timing(offsetRef, {
      toValue: ScreenHeight - usableScreenHeight,
      duration: 500,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start(() => {});
  }, [offsetRef]);

  const closeAnimated = useCallback(() => {
    Animated.timing(offsetRef, {
      toValue: ScreenHeight + 1000,
      duration: 300,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start(() => {
      onDismiss?.();
    });
  }, [offsetRef, onDismiss]);

  useEffect(() => {
    startAnimated();
  }, [params, startAnimated]);

  return (
    <Animated.View style={[{transform: [{translateY: offsetRef}]}]}>
      <View style={styles.episodes_model_container}>
        <Header onDismiss={closeAnimated} />
        <View style={styles.episodes_menu}>
          <EpisodeTabs length={96} />
          <View style={{flex: 1}}>
            <FlatList
              data={episodes}
              numColumns={6}
              keyExtractor={(item, index) => index.toString() + item}
              columnWrapperStyle={{
                justifyContent: 'space-between',
                marginBottom: 10,
              }}
              contentContainerStyle={{
                paddingBottom: 20,
                paddingVertical: normalize(10),
              }}
              renderItem={({item}) => (
                <TouchableOpacity style={styles.episodes_item}>
                  <BasicText color="hsla(0,0%,100%,.6)">{item}</BasicText>
                </TouchableOpacity>
              )}
            />
          </View>
        </View>
      </View>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  episodes_model_container: {
    height: normalize(450),
    width: ScreenWidth,
    backgroundColor: '#191919',
    position: 'absolute',
    bottom: 0,
    borderTopRightRadius: normalize(16),
    borderTopLeftRadius: normalize(16),
  },
  header_view: {
    height: normalize(49),
    display: 'flex',
    paddingHorizontal: normalize(16),
    paddingVertical: normalize(8),
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  episodes_menu: {
    flex: 1,
    paddingHorizontal: normalize(8),
    paddingBottom: normalize(8),
    display: 'flex',
  },
  episodes_tabs: {
    display: 'flex',
    flexDirection: 'row',
    gap: normalize(10),
  },
  episodes_scroll_list: {
    flex: 1,
  },
  episodes_item: {
    width: normalize(45),
    height: normalize(45),
    borderWidth: normalize(1),
    borderStyle: 'solid',
    borderColor: '#666',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: normalize(6),
  },
});

export default EpisodesModal;
